package top.sdwu_top.kbase.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import sun.awt.SunHints;
import top.sdwu_top.kbase.entity.KbaseFile;
import top.sdwu_top.kbase.entity.KbaseFileVersion;
import top.sdwu_top.kbase.mapper.KbaseFileVersionMapper;
import top.sdwu_top.kbase.service.IKbaseFileVersionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.sdwu_top.kbase.vo.KbaseFileVersionVo;

import java.util.Objects;

/**
 * <p>
 * 文件版本 服务实现类
 * </p>
 *
 * @author zhipeng.duan@nvr-china.com
 * @since 2020-02-20
 */
@Service
public class KbaseFileVersionServiceImpl extends ServiceImpl<KbaseFileVersionMapper, KbaseFileVersion> implements IKbaseFileVersionService {

    @Override
    public KbaseFileVersion getLastOne(String fileId) {
        if (StringUtils.isBlank(fileId)) {
            return new KbaseFileVersion();
        }
        QueryWrapper<KbaseFileVersion> qw = Wrappers.query();
        qw.eq("FILE_ID", fileId);
        qw.orderByDesc("version");
        qw.last("limit 1");
        KbaseFileVersion fileVersion = super.getOne(qw);
        if (Objects.isNull(fileVersion)) {
            return new KbaseFileVersion();
        }
        return fileVersion;
    }

    @Override
    public Integer getLastVersion(String fileId) {
        Integer version = getLastOne(fileId).getVersion();
        return Objects.isNull(version) ? -1 : version;
    }

    @Override
    public KbaseFileVersion getByFileIdAndVersion(String fileId, Integer version) {
        QueryWrapper<KbaseFileVersion> qw = Wrappers.query();
        qw.eq("FILE_ID", fileId)
                .eq("VERSION", version);
        qw.last("limit 1");
        return super.getOne(qw);
    }

    @Override
    public Page<KbaseFileVersion> page(KbaseFileVersionVo vo) {
        if (StringUtils.isBlank(vo.getFileId())) {
            return vo.getPage();
        }
        QueryWrapper<KbaseFileVersion> qw = Wrappers.query();
        qw.eq("v.FILE_ID", vo.getFileId());
        qw.orderByDesc("v.VERSION");
        return super.getBaseMapper().myPage(vo.getPage(), qw);
    }
}
